package com.which.one;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.which.one.deepseek.Message;
import com.which.one.deepseek.MessageAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DeepseekActivity extends AppCompatActivity {
    private static final long TIMEOUT_SECONDS = 30;
    private RecyclerView recyclerView;
    private EditText inputEdit;
    private Button sendBtn;
    private List<Message> messages = new ArrayList<>();
    private MessageAdapter adapter;

    private static final String API_KEY = "sk-07ba215eef874dabaf391816d3f55dd8";
    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private static final String MODEL_NAME = "deepseek-chat";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        recyclerView = findViewById(R.id.recycler_view);
        inputEdit = findViewById(R.id.input_edit);
        sendBtn = findViewById(R.id.send_btn);

        // 设置RecyclerView
        adapter = new MessageAdapter(messages);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);


        sendBtn.setOnClickListener(v -> {
            String input = inputEdit.getText().toString().trim();
            if (!input.isEmpty()) {
                // 添加用户消息
                messages.add(new Message(input, true));
                adapter.notifyItemInserted(messages.size() - 1);
                inputEdit.setText("");
                recyclerView.scrollToPosition(messages.size() - 1);

                // 发送API请求
                sendToAPI(input);
            }
        });

        // 临时测试：5秒后强制显示消息
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            adapter.notifyDataSetChanged();
            recyclerView.scrollToPosition(0);

            // 打印布局尺寸
            recyclerView.post(() -> {
                Log.e("LAYOUT_FORCE", "RecyclerView 高度: " + recyclerView.getHeight());
                Log.e("LAYOUT_FORCE", "RecyclerView 可见性: " + recyclerView.getVisibility());
            });
        }, 5000);
    }

    private void sendToAPI(String message) {
        OkHttpClient client = new OkHttpClient.Builder()
                //超时延长
                .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .build();

        try {
            JSONObject json = new JSONObject();
            json.put("model", MODEL_NAME); // 模型名称修正


            JSONArray messagesArray = new JSONArray();
            JSONObject msg = new JSONObject();
            msg.put("role", "system");
            msg.put("content", message);
            messagesArray.put(msg);
            json.put("messages", messagesArray);
            json.put("stream", false);

            // 打印调试信息
            Log.e("API_REQUEST", "请求JSON:\n" + json.toString(2));

            RequestBody body = RequestBody.create(json.toString(), MediaType.parse("application/json"));
            Request request = new Request.Builder()
                    .url(API_URL)
                    .post(body)
                    .addHeader("Authorization", "Bearer sk-07ba215eef874dabaf391816d3f55dd8")
                    .addHeader("Content-Type", "application/json")
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("API_FAILURE", "请求失败", e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseBody = response.body().string();
                    Log.e("API_STATUS", "状态码: " + response.code());
                    Log.e("API_RAW", "原始响应:\n" + responseBody);

                    try {
                        JSONObject jsonResponse = new JSONObject(responseBody);
                        String aiResponse = jsonResponse.getJSONArray("choices")
                                .getJSONObject(0)
                                .getJSONObject("message")
                                .getString("content");

                        runOnUiThread(() -> {
                            messages.add(new Message(aiResponse, false));
                            adapter.notifyItemInserted(messages.size() - 1);
                            recyclerView.smoothScrollToPosition(messages.size() - 1);
                        });
                    } catch (JSONException e) {
                        Log.e("API_PARSE", "解析异常", e);
                        Log.e("API_ERROR", "错误响应内容:\n" + responseBody);
                    }
                }
            });
        } catch (JSONException e) {
            Log.e("API_BUILD", "JSON构造失败", e);
        }
    }

}